<?php
declare(strict_types=1);

namespace App\Logic\Exam;

use App\Library\SnowFlakeId;
use App\Logic\BaseUserService;
use App\Model\User\Exam\UserCollection;
use App\Model\User\Exam\UserCollectionReadingRel;
use App\Model\User\Exam\UserCollectionSubmitUserHistory;
use App\Model\User\Exam\UserReading;
use App\Model\User\Exam\UserReadingCollectionHistory;
use App\Model\User\Exam\UserReadingSubmitHistory;
use Closure;
use Exception;

/**
 * @project: 兔兔考试系统
 * @author: Mandy
 * @date: 2023/7/19
 * @link: https://www.tutudati.com/
 * @site: 微信搜索-兔兔考试系统
 */
class ReadingService extends BaseUserService
{
    private function searchWhere(): Closure
    {
        return function ($query) {
            $requestParams = request()->all();
            $query->where("is_show", "=", 1);
            if (!empty($requestParams["collection_uid"])) {
                $query->where("collection_uid", "=", $requestParams["collection_uid"]);
            }
            if (!empty($requestParams["uid"])) {
                $query->where("uid", "=", $requestParams["uid"]);
            }
        };
    }

    // 获取阅读理解试题列表
    public function getList(): array
    {
        $requestParams = request()->all();
        $examUid = UserCollectionReadingRel::query()
            ->where("collection_uid", "=", $requestParams["collection_uid"])
            ->get(["exam_uid"])
            ->toArray();
        if (empty($examUid)) {
            return [
                "items" => [],
                "isVip" => $this->getVipState() == 1
            ];
        }
        $examUidArray = array_column($examUid, "exam_uid");
        $items = UserReading::query()
            ->whereIn("uid", $examUidArray)
            ->where([
                ["is_show", "=", 1],
            ])
            ->get(["uid", "title", "is_free"])
            ->toArray();
        return [
            "items" => $items,
            "isVip" => $this->getVipState() == 1,
        ];
    }

    // 获取试题详情
    public function content(): array
    {
        $requestParams = request()->all();
        $bean = UserReading::query()->where($this->searchWhere())->first(["uid", "content", "title", "submit", "collect", "collection_uid"]);
        if (!empty($bean)) {
            try {
                // 添加试卷记录和试题记录
                UserReading::query()->where([["uid", "=", $bean->uid]])->increment("submit");
                UserReadingSubmitHistory::query()->create([
                    "reading_uid" => $requestParams["uid"],
                    "user_uid" => $this->getUserUid(),
                    "uid" => SnowFlakeId::getId()
                ]);
            } catch (Exception $exception) {
                // todo 添加日志
            }
        }
        return !empty($bean) ? $bean->toArray() : [];
    }

    public function submitGroupList(): array
    {
        $requestParams = request()->all();
        $collectionInfo = UserReading::query()
            ->where("uid", "=", $requestParams["uid"])
            ->first(["submit", "collect"]);
        $items = UserReadingSubmitHistory::query()
            ->with(["user:nickname,avatar_url,uid"])
            ->where([
                ["reading_uid", "=", $requestParams["uid"]]
            ])->paginate(6, ["user_uid"]);
        $isSubmit = $isCollection = 0;
        if (!empty($this->getUserUid())) {
            $submitHistory = UserReadingSubmitHistory::query()->where([
                ["user_uid", "=", $this->getUserUid()],
                ["reading_uid", "=", $requestParams["uid"]]
            ])->first(["id"]);
            $collectionHistory = UserReadingCollectionHistory::query()->where([
                ["user_uid", "=", $this->getUserUid()],
                ["reading_uid", "=", $requestParams["uid"]]
            ])->first(["id"]);
            if (!empty($submitHistory)) {
                $isSubmit = 1;
            }
            if (!empty($collectionHistory)) {
                $isCollection = 1;
            }
        }
        return [
            "list" => $items->items(),// 答题列表
            "count" => $items->total(),// 答题总人数
            "submit" => $collectionInfo["submit"],// 答题总人数
            "collect" => $collectionInfo["collect"],// 收藏总数
            "is_submit" => $isSubmit == 1,// 是否答题
            "is_collection" => $isCollection == 1,// 是否收藏
        ];
    }
}
